package cn.mugutu.find;

import org.junit.Test;

import java.util.Arrays;

/**
 * Created by gan on 2018/3/21 14:24.
 */
public class BinarySearch {


    //二分法查找
    @Test
    public void binarySearch() {
        //一个排好序的数组,数组中没有重复的元素
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};

        int halfIndex = arr.length / 2;
        int resutlIndex = halfIndex;

        int lastIdex = arr.length - 1;
        int firstIndex = 0;

        //要查找的数据
        int target = 10;

        while (true) {
            if (target == arr[halfIndex]) {
                resutlIndex = halfIndex;
                break;
            } else if (target > arr[halfIndex]) {
                firstIndex = halfIndex;
                halfIndex = (halfIndex + lastIdex) / 2;
            } else {
                lastIdex = halfIndex;
                halfIndex = (firstIndex + halfIndex) / 2;
            }

            if (firstIndex + 1 >= lastIdex) {
                System.out.println("==========沒有找到==>" + target);
                return;
            }
        }


        System.out.println("結果索引为===>" + resutlIndex);
    }

    @Test
    public void test1() {
        int[] arr = {1, 2, 32, 3};
        Arrays.sort(arr);
    }


    @Test
    public void test2() {
        String t1 = "hello";
        String t2 = "hello";

        System.out.println(t1 == t2);
    }
}
